<?php
/**
 * Created by PhpStorm.
 * User: djh
 * Date: 2016/11/10
 * Time: 17:53
 */

namespace member\action;
use herosphp\http\HttpRequest;
use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\web\WebUtils;
use member\service\LoginService;
use member\service\RegisterService;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;

Loader::import('member.service.LoginService');
Loader::import('member.service.RegisterService');

class LoginAction extends CommonAction{

    public function index(HttpRequest $request){
		$dir = urldecode($request->getParameter('dir'));
		if($_POST)
		{
			$this->login($request);
		}
		//是否开启验证码验证
		$settingService = Beans::get('admin.adminSetting.service');
		$verifyCodeEnable = $settingService->getSetting('verifyCode');
		$this->assign('verifyCodeEnable',$verifyCodeEnable);
        Session::start();
        if(time() - $_SESSION['error_time'] > 300){
            unset($_SESSION['error_times']);
        }
        if( $_SESSION['error_times'] > 3 ){
            $this->assign('verifyCodeEnable','on');
        }
		$this->assign('dir',$dir);
		$service = new LoginService();
		if ( $service->hasLogin() ) {
			header('location:'.$dir);
        }
		$this->assign('dir' ,$dir);

        $ad = Beans::get("information.informationAd.service")->getItem(array('ad_place_key'=>'18574d4e4a60013d9d7e46af6ea2906b'));
        $this->assign('adBanner',$ad);
        $this->setView('login/login_index');
    }

	public function login(HttpRequest $request)
	{

		$username = $request->getParameter('username');
		$password = $request->getParameter('pwd');
		$vcode = $request->getParameter('vcode');
		$dir = urldecode($request->getParameter('dir'));

        Session::start();
        if( $_SESSION['error_times'] > 5 ){
            $service = new LoginService();
            $service -> setLastError($username);
            $this->assign('wrong',"密码连续错误5次，请5分钟之后再尝试登录");
            return;
        }

		$settingService = Beans::get('admin.adminSetting.service');
		$denyIp = $settingService->getSetting('denyLoginIp');
		$iplist = explode(',',$denyIp);
		
		$ip = WebUtils::getClientIP();

		//ip校验
		foreach($iplist as $v){
			if(matchIp($ip,$v)){
				$this->assign('wrong',L('LOGIN_IP_DENY'));
				return ;
			}
		}
		$verifyCodeEnable = $settingService->getSetting('verifyCode');


		//是否开启验证码验证
		if($verifyCodeEnable == 'on' || $_SESSION['error_times'] > 3 ){
            $verify_expr = C('verify_expr')?C('verify_expr'):30;
			if ( time() - $_SESSION['scode_time'] > $verify_expr ) {
                $this->assign('wrong',L('VERIFY_EXPR_ERROR'));
                return;
            }
			else if ( strtoupper($vcode) != $_SESSION['scode'] ) {
				$this->assign('wrong',L('LOGIN_VCODE_ERROR'));
				return ;
			}
		}


        $service = new LoginService(); 
        $user = $service->login($username, $password);
        if ( $user == false ) {
            //记录登陆错误次数，超过三次开启验证码
            if( !$_SESSION['error_times'] ){
                $_SESSION['error_times'] = 1;
            }
            $_SESSION['error_times']++;
            $_SESSION['error_time'] = time();
			$this->assign('wrong',L('LOGIN_ERROR'));
			return ;
        }else{
            if( $user['status'] == "0" ){
                $this->assign('wrong',"账户已被禁用");
                return ;
            }elseif ( $user['status'] == "-1" ){
                $_SESSION['error_times'] = 5;
                $this->assign('wrong',"密码连续错误5次，请5分钟之后再尝试登录");
                return;
            }
        }
        $_SESSION['error_times'] = null;

		if($dir && strpos($dir,"reg") ===false){
			header('Location:'.$dir);
		}
		else{
			header('Location:'.url('/member/index/index'));
		
		}
		exit(0);
        //AjaxResult::ajaxSuccessResult();
	}
	
	public function logout(HttpRequest $request)
	{
        $service = new LoginService(); 
		$service->logout();
		header('Location:'.url('/member/login').'?dir='.$_SERVER['HTTP_REFERER']);
		exit(0);

	}

    /**
     * @param HttpRequest $request
     * 找回密码
     */
    public function forget(HttpRequest $request){
        $this -> assign('step',1);
        $this -> setView('login/login_forget');
    }

    public function do_forget(HttpRequest $request) {


        $step = $request -> getParameter('step');
        if( $step == 1 ) {
            $username = $request->getParameter('username');
            $vcode = $request->getParameter('vcode');
            $service = new RegisterService();
            $result = $service->hasRegister($username);
            if($result) {
                $this -> timeOut();
                if($vcode==$_SESSION['mpe_member']['vcode']) {
                    $token = md5(md5($username.time()));
                    $_SESSION['token'] = $token;//TODO  设置token的过期时间
                    $_SESSION['token_expire'] = time();
                    $_SESSION["username"] = $username;
                    AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, array('token' => $token));
                }else {
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "验证码不正确", null);
                }
            }else {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "该手机号码还没注册", null);
            }
        }else{
            //时间过期
            if( time() - $_SESSION['token_expire'] >120 ){
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "页面已失效", null);
            }
            $token = $request->getParameter('token');
            $pwd = $request->getParameter('pwd');
            $username = $_SESSION["username"] ;
            if($token!=$_SESSION["token"]){
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "页面已失效", null);
            }else {
                $service =  Beans::get('member.member.service');
                $item = $service -> getItem(array("username" => $username,"del_status"=>0),"password",null);
                if( $item ){
                    if( $item['password'] == passwd($pwd) ){
                        AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "新密码不能与原密码相同", null);
                    }
                }
                $bool = $service -> updates(array('password' => passwd($pwd)),array("username" => $username,"del_status"=>0));
                unset($_SESSION["token"]);
                if($bool) {
                    AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "密码修改成功", null);
                }else {
                    Log::error($username."密码修改失败");
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "密码修改失败", null);

                }
            }

        }

    }
}
